from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, GenericAPIView, UpdateAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from areas.models import Area
from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users.serializers import RegisterCreateSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer, \
    AddressTitleSerializer, UserHistorySerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from users.models import User

"""用户地址管理"""

# 用户地址新增与修改
# list GET: /users/addresses/
# create POST: /users/addresses/
# destroy DELETE: /users/addresses/
# action PUT: /users/addresses/pk/status/
# action PUT: /users/addresses/pk/title/


"""扩展登陆"""


class UserAuthorizationView(ObtainJSONWebToken):
    """
    # 1.调用jwt登陆方法
    # 2.校验用户是否登陆成功,合并购物车数据
    # # 创建序列化,对数据进行校验
    # #校验通过获取user信息
    # # 合并购物车数据
    # 返回响应
    """

    def post(self, request, *args, **kwargs):
        # 1.调用jwt登陆方法
        response = super().post(request)
        # 2.校验用户是否登陆成功,合并购物车数据
        # # 创建序列化,对数据进行校验
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # #校验通过获取user信息
            user = serializer.validated_data.get("user")
            # # 合并购物车数据
            response = merge_cart_cookie_to_redis(request, user, response)
        # 返回响应
        return response


class AddressViewSet(ModelViewSet):
    # 增加序列化器,获取用户输入的数据,并进行校验
    serializer_class = AddressSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = None

    # 由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    """新增地址"""

    def create(self, request, *args, **kwargs):
        count = request.user.addresses.count()
        if count > 20:
            return Response({'message': '保存地址数量已经达到上限'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return super().create(request, *args, **kwargs)

    """地址列表"""

    def list(self, request, *args, **kwargs):
        # 获取逻辑删除外的该用户所有地址
        queryset = self.get_queryset()
        # 将查询到的查询结果集转化成json数据，传到前端页面．(进行序列化)
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 将数据返回前端页面
        data = {
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        }
        return Response(data)

    """删除地址"""

    def delete(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    """修改地址标题"""

    @action(methods=['put'], detail=True)
    def title(self, request, *args, **kwargs):
        address = self.get_object()
        # 创建序列化器，对用户输入的标题进行校验和修改
        serializer = AddressTitleSerializer(address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    """设置默认值"""

    @action(methods=['put'], detail=True)
    def status(self, request, *args, **kwargs):
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


"""验证邮箱链接"""


class VerificationEmailView(APIView):
    # 1.获取token的值
    # 2.根据token获取id
    # 3.根据id 查询用户信息
    # 4.修改邮箱激活字段
    def get(self, request):
        token = request.query_params.get('token')

        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        user = User.check_verify_email_token(token)
        if not user:
            return Response({'message': '链接失效'})
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'ok'})


"""保存邮箱"""


class EmailView(UpdateAPIView):
    # 用户应该是认证过的用户,将用户邮箱进行保存
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user


"""用户中心"""


# 能够进入用户中心的一定是登陆用户,所以需要用到认证
class UserDetailView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get(self, request):
        # 获取到用户模型,进行序列化,将数据返回
        # 获取到用用户模型
        user = request.user
        # 进行序列化
        serializer = self.get_serializer(user)
        # 将数据返回
        return Response(serializer.data)


"""注册"""


class RegisterCreateView(CreateAPIView):
    serializer_class = RegisterCreateSerializer


"""用户名"""


# 请求方式： GET /users/usernames/(?P<username>\w{5,20})/count/
# 请求参数: usename
# 返回数据: json  返回值 count usename
class RegisterUsernameCountAPIView(APIView):
    """
        获取用户名的个数
        GET:  /users/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self, request, username):
        # 通过用户名查询该用户名用户个数
        count = User.objects.filter(username=username).count()
        # 将返回值返回给前端
        context = {
            'count': count,
            'username': username
        }
        return Response(context)


"""手机号"""


class RegisterPhoneCountAPIView(APIView):
    """
    查询手机号的个数
    GET: /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """

    def get(self, request, mobile):
        # 通过手机号码查询该手机号的用户个数
        count = User.objects.filter(mobile=mobile).count()
        context = {
            'count': count,
            'mobile': mobile
        }
        return Response(context)


class UserHistoryView(GenericAPIView):
    # 保存历史记录
    """
    1.记录登陆用户的历史记录
    2.前端发送请求，包括用户信息和商品id
    3．校验商品id　是否存在
    4.将用户信息保存在redis里
    """
    permission_classes = [IsAuthenticated]
    serializer_class = UserHistorySerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'message': 'ok'})

    # 查看历史记录
    # 1.连接到redis
    # 获取用户id
    # 2.根据用户id 获取到对应的所有商品id (列表)
    # 3.遍历所有的商品id,查找相应对象，创建一个对象列表
    # 4.将模型数据转换成jSON数据(序列化),传到前端
    def get(self, request):
        # 1.连接到redis
        redis_conn = get_redis_connection('history')
        # 获取用户id
        user_id = request.user.id
        # 2.根据用户id 获取到对应的所有商品id (列表)
        history_sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)
        # 3.遍历所有的商品id,查找相应对象，创建一个对象列表
        skus = []
        for sku_id in history_sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            skus.append(sku)
        # 4.将模型数据转换成jSON数据(序列化--->创建一个关于SKU模型的序列化器)传到前端
        serializer = SKUSerializer(instance=skus, many=True)
        return Response(serializer.data)
